﻿using CRM_S.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace CRM_S.Controllers
{
    public class UsersController : ApiController
    {
        // GET: api/Users
        [HttpGet]
        public IHttpActionResult user(string loginName, string isLockout, int page = 1, int limit = 10)
        {
            using (cremEntities db = new cremEntities())
            {
                var datalist = db.Users.AsEnumerable();
                datalist = datalist.Where(p => p.isShow == 1);
                if (!string.IsNullOrEmpty(loginName))
                {
                    datalist = datalist.Where(p => p.loginName.Contains(loginName));
                }
                if (!string.IsNullOrEmpty(isLockout))
                {
                    datalist = datalist.Where(p => p.isLockout ==Convert.ToInt32(isLockout));
                }
                var count = datalist.Count();
                var list = datalist.Select(p => new {
                    uid = p.uid,
                    loginName = p.loginName,
                    password = p.password,
                    isLockout = p.isLockout,
                    //LastLoginTime = p.LastLoginTime.ToString(),
                    createTime = p.createTime.ToString(),
                    //PsdWrongTime = p.PsdWrongTime,
                    lockTime = p.lockTime.ToString(),
                    email = p.email,
                    phone = p.phone,
                    State=p.isShow
                }).Skip((page - 1) * limit).Take(limit).ToList();
                return Json(new { count = count, data = list });
            }
        }
        [HttpPost]
        public IHttpActionResult addUsers([FromBody]User add)
        {
            using (cremEntities db = new cremEntities())
            {
                add.createTime = DateTime.Now;
                add.isLockout = 1;
                add.errorCount = 0;
                add.isShow = 1;
                db.Users.Add(add);
                int n = db.SaveChanges();
                if (n > 0)
                {
                    return Json(new { code = 0, msg = "添加成功！" });
                }
                else
                {
                    return Json(new { code = -1, msg = "添加失败！" });
                }
            }
        }
        [HttpPost]
        public IHttpActionResult Edit([FromBody]User add)
        {
            using (cremEntities db = new cremEntities())
            {
                var list = db.Users.FirstOrDefault(p => p.uid == add.uid);
                list.loginName = add.loginName;
                list.email = add.email;
                list.phone = add.phone;
                int n = db.SaveChanges();
                if (n > 0)
                {
                    return Json(new { code = 0, msg = "修改成功！" });
                }
                else
                {
                    return Json(new { code = -1, msg = "修改失败！" });
                }
            }
        }
        [HttpPost]
        public IHttpActionResult Delete([FromBody]User user)
        {
            using (cremEntities db = new cremEntities())
            {
                var list = db.Users.FirstOrDefault(p => p.uid == user.uid);
                list.isShow = 0;
                int n = db.SaveChanges();
                if (n > 0)
                {
                    return Json(new { code = 0, msg = "删除成功！" });
                }
                else
                {
                    return Json(new { code = -1, msg = "删除失败！" });
                }
            }
        }

        public IHttpActionResult Idlockout([FromBody] User ff)
        {
            using (cremEntities db = new cremEntities())
            {
                var list = db.Users.FirstOrDefault(p => p.uid == ff.uid);
                if (list.isLockout == 1)
                {
                    list.isLockout = 0;
                    list.lockTime = DateTime.Now;
                    int m = db.SaveChanges();
                    if (m > 0)
                    {
                        return Json(new { code = 0, msg = "锁定成功！" });
                    }
                    else
                    {
                        return Json(new { code = -1, msg = "锁定失败！" });
                    }
                }
                else
                {
                    list.isLockout = 1;
                    list.lockTime = null;
                    list.errorCount = 0;
                    int n = db.SaveChanges();
                    if (n > 0)
                    {
                        return Json(new { code = 0, msg = "解除锁定成功！" });
                    }
                    else
                    {
                        return Json(new { code = -1, msg = "解除锁定失败！" });
                    }
                }
            }
        }

        [HttpGet]
        public IHttpActionResult GetRoles(int Id)
        {
            using (cremEntities db = new cremEntities())
            {
                var list = db.UserRoles.Where(t => t.UserId == Id).ToList();
                var Roleslist = db.Roles.Select(t => new { key = t.rid, label = t.rname }).ToList();
                if (list.Count > 0)
                {
                    var ss = "";
                    foreach (var item in list)
                    {
                        ss += Convert.ToString(item.RoleId) + ",";
                    }

                    ss = ss.Substring(0, ss.Length - 1);
                    var mo = ss.Split(',').Select(x => int.Parse(x)).ToList();

                    return Json(new { code = 0, data = Roleslist, valus = mo, userId = Id });
                }
                else
                {
                    return Json(new { code = -1, data = Roleslist, valus = "", userId = Id });
                }

            }
        }

        [HttpGet]
        public IHttpActionResult GetUsersRolesAdd(int userId, string movedKey)
        {
            using (cremEntities db = new cremEntities())
            {
                var mo = movedKey.Split(',').Select(x => int.Parse(x)).ToList();
                for (int i = 0; i < mo.Count; i++)
                {
                    UserRole ur = new UserRole() { UserId = userId, RoleId = mo[i] };
                    db.UserRoles.Add(ur);
                }
                //char[] ss = movedKeys.ToCharArray();
                //foreach (var item in ss)
                //{
                //    UserRoles ur = new UserRoles() { UserId = UserId, RoleId = item };
                //    db.UserRoles.Add(ur);
                //}
                
                int n = db.SaveChanges();
                if (n > 0)
                {
                    return Json(new { code = 0, msg = "添加成功" });
                }
                else
                {
                    return Json(new { code = -1, msg = "添加失败" });
                }
            }
        }


        //重置 Resert
        public IHttpActionResult Resert([FromBody] User user)
        {
            using (cremEntities db = new cremEntities())
            {
                var list = db.Users.FirstOrDefault(p => p.uid == user.uid);
                if (list != null)
                {
                    list.password = list.phone.Substring(5, 6) + 123;
                    int n = db.SaveChanges();
                    if (n > 0)
                    {
                        return Json(new { code = 0, msg = "重置成功" });
                    }
                    else
                    {
                        return Json(new { code = -1, msg = "重置失败" });
                    }
                }
                else
                {
                    return Json(new { code = -2, msg = "错误操作" });
                }
            }
        }
    }
}
